package com.zerox.controller;

import com.alibaba.fastjson.JSON;
import com.zerox.domain.TableVO;
import com.zerox.pojo.SysUser;
import com.zerox.service.SysUserService;
import javafx.scene.control.Tab;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
//@Component
//@Service 业务逻辑的Bean
//@Repository 数据访问的Bean
//@Controller 控制器的Bean

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private SysUserService sysUserService;

    @GetMapping("/toList")
    public String toList(){
        return "list";
    }

    @GetMapping(value = "/userList",produces = {"application/json;charset=utf-8"})
    public void list( HttpServletResponse response, Integer page, Integer limit,String realName,Integer roleId)throws IOException {

        List<SysUser> userList = sysUserService.list(page, limit, realName, roleId);
//        int result = sysUserService.result();
        TableVO tableVO = new TableVO(0, 100, userList, "");
        int count = sysUserService.count(realName,roleId);

        TableVO tableVO1 = new TableVO(0, count, userList, "");
        String json =  JSON.toJSONString(tableVO);
        response.getWriter().print(json);
    }

    //    @RequestMapping(value = "/add",method = RequestMethod.POST)

    @GetMapping("/addTo")
    public String toAdd(){
        return "Add_to";
    }

    @PostMapping("/AddTo")
    public String Add(HttpServletRequest request,Model model, @Valid SysUser sysUser, BindingResult bindingResult,MultipartFile idPic) throws IOException {

        if (bindingResult.hasErrors()){

            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors){
                model.addAttribute(fieldError.getField()+"Error",fieldError.getDefaultMessage());
            }
            return "Add_to";
        }
        if (idPic.getSize()>2000000){
            model.addAttribute("idPicError","文件超过2M不能上传");
            return "Add_to";
        }
        // 指定文件存储的目录
        String path = request.getSession().getServletContext().getRealPath("static")+File.separator+"upload";
        //自定义 文件名
        String suffix = idPic.getOriginalFilename().substring(idPic.getOriginalFilename().lastIndexOf("."));
        if (".jpg.png".indexOf(suffix)==-1){
            model.addAttribute("idPicError","文件格式不正确，不能上传");
            return "Add_to";
        }
        String fileName = RandomUtils.nextInt(1000000)+"_pic"+suffix;
        File fileTo = new File(path+File.separator+fileName);
        //如果文件不存在就创建
        if (!fileTo.exists()){
            fileTo.mkdirs();
        }

        //核心代码： 将文件存储到指定位置
        idPic.transferTo(fileTo);
        sysUser.setIdPicPath(fileName);
        int result = sysUserService.add(sysUser);

        if (result>0){
            return "redirect:toList";
        }
        model.addAttribute("errorMsg","新增失败");
        return "forward:toupdate/"+sysUser.getId();
    }

    @PostMapping("/add")
    public ModelAndView add() {
        System.out.println();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("add.jsp");
        return modelAndView;
    }

    //    @RequestMapping(value = "/list",method = RequestMethod.GET)



    @GetMapping("/list2")
    public String list2(Map<String, Object> map, @RequestParam(value = "ids", required = false, defaultValue = "0") Integer id) {
        System.out.println(id);
        map.put("id", id);
        return "forward:list";
    }



    @GetMapping("/view/{userid}")
    public String view(Model model,@PathVariable("userid") Integer id){
        SysUser sysUser = sysUserService.selectById(id);
        System.out.println(sysUser);
        model.addAttribute("sysUser",sysUser);
        return "view";
    }
    @GetMapping("/delete/{id}")
    @ResponseBody
    public String delete(@PathVariable Integer id){

        int result = sysUserService.delete(id);

        return result>0 ? "1" : "0";
    }

    @GetMapping("toupdate/{id}")
    public String Update(Model model,@PathVariable Integer id){
        SysUser sysUser = sysUserService.selectById(id);
        model.addAttribute("sysUser",sysUser);
        return "update";
    }

    @PostMapping("/update")
    public String update(Model model, HttpServletRequest request,@Valid SysUser sysUser,BindingResult bindingResult){

        if (bindingResult.hasErrors()){
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors){
                model.addAttribute(fieldError.getField()+"Error",fieldError.getDefaultMessage());
            }
            return "update";
        }

        int result = sysUserService.update(sysUser);
        if (result>0){
            return "list";
        }
        model.addAttribute("errorMsg","新增失败");

        return "update";
    }

    @GetMapping("/accountExists")
    @ResponseBody
    public String accountExists(String account){
        SysUser sysUser = sysUserService.selectByAccount(account);
        return sysUser==null?"true":"false";
    }

    @GetMapping(value = "/view2{userid}",produces = "application/json;charset=utf-8")
    @ResponseBody
    public SysUser ViewTo(@PathVariable("userid") Integer id,Model model){

        SysUser sysUser = sysUserService.selectUserId(id);
        return sysUser;

    }
}